﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

using Admin.NET.Application.Util.Extension;
using Admin.NET.Interface.Kingdee.Util.Extension;
using Radius.NET.Application.Const;
using Radius.NET.Interface.Kingdee.Entity;

namespace Radius.NET.Interface.Kingdee.Service.BasicInfoModule;
/// <summary>
/// 基础资料服务
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 002)]
public class MisCustomerService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<MisCustomer> misCustomerRespository;

    private readonly KingdeeUtil _kingdeeUtil;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="_misCustomerRespository"></param>
    /// <param name="kingdeeUtil"></param>
    public MisCustomerService(SqlSugarRepository<MisCustomer> _misCustomerRespository,
        KingdeeUtil kingdeeUtil)
    {
        misCustomerRespository = _misCustomerRespository;
        _kingdeeUtil = kingdeeUtil;
    }


    #region 同步金蝶云星空客户档案到本地
    /// <summary>
    /// 同步金蝶云星空客户档案到本地
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/basicinfo/miscustomerlist/{cid}"), AllowAnonymous]
    public async Task<object> SyncMisCustomerList(int cid, string BDate)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_basicinfo_miscustomerlist");
        List<MisCustomer> misCustomers = new();
        List<MisCustomer> misCustomers_update = new();
        List<string> ContactNumList = new();
        string filekeys = $"FUseOrgId.FNumber = '{KingdeeConfigConst.ORGID}' and FForbidStatus = 'A' ";
        if (!string.IsNullOrEmpty(BDate) && DateTime.TryParse(BDate,out DateTime FCreateDate))
        {
            filekeys += $" and FCreateDate >='{FCreateDate:yyyy-MM-dd}'";
        }

        //获取云星空BOM清单
        var list = KingdeeUtil.Query<BD_Customer_Dto>("BD_Customer", filekeys);

        if (list.Count == 0)
        {
            throw Oops.Oh("金蝶无数据可同步！");
        }

        //循环客户档案插入本地表
        foreach (var item in list)
        {
            MisCustomer obj = new()
            {
                ContactNum = item.FNumber,
                ContactName = item.FName,
                Status = item.FForbidStatus == "A" ? 0 : 1,
                OptionalNameSecond = item.FShortName,
                CustType = "正式客户",
                Address = item.FAddress,
                Phone = item.FTel,
                CurrencyType = item.FTradingCurridFNumber,
                DeptLead = item.FSaldeptIdFNumber,
                PayMent = item.FSettleTypeIdFNumber,
                CustTypeID = item.FCustTypeIdFNumber,
                TaxType = item.FInvoiceType,
                Salesman = item.FSellerFNumber,
                CreateDate = item.FCreateDate,
                CountryID = item.FCountryFDataValue,
                City = item.FCityFDataValue,
                BillingState = item.FProvincialFDataValue,
                _cid = cid,
            };
            if (!ContactNumList.Any(x => x == item.FNumber))
            {
                //判断客户档案是否存在
                if (!await misCustomerRespository.IsAnyAsync(x => x.ContactNum == item.FNumber))
                {
                    misCustomers.Add(obj);
                } else {
                    misCustomers_update.Add(obj);
                }
                ContactNumList.Add(item.FNumber);
            }
        }
        if (misCustomers.Count == 0 && misCustomers_update.Count == 0)
        {
            throw Oops.Oh("当前同步的客户本系统中已存在！");
        }

        try
        {
            //misCustomerRespository.Context.Ado.BeginTran();
            var obj = await misCustomerRespository.AsInsertable(misCustomers).ExecuteCommandAsync();
            obj = await misCustomerRespository.AsUpdateable(misCustomers_update)
                .UpdateColumns(x => new
                {
                    x.ContactName,
                    x.Status,
                    x.OptionalNameSecond,
                    x.Address,
                    x.Phone,
                    x.CurrencyType,
                    x.DeptLead,
                    x.PayMent,
                    x.CustTypeID,
                    x.TaxType,
                    x.Salesman,
                    x.CountryID,
                    x.City,
                    x.BillingState
                }).ExecuteCommandAsync();
            //misCustomerRespository.Context.Ado.CommitTran();
            return obj;
        }
        catch (Exception ex)
        {
            //misCustomerRespository.Context.Ado.RollbackTran();
            throw Oops.Oh(ex.Message);
        }
    }
    #endregion

}
